package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LeYouException;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.utils.CodeUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Rose
 * @Date: 2021/4/9 22:51
 * @description ${description}
 * @version: 1.0.0
 */
@Service
public class UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public static final String KEY_PREFIX = "user:verify:phone:";


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 用户名或手机号 唯一性校验
     *
     * @param data
     * @param type
     * @return
     */
    public Boolean checkData(String data, Integer type) {

        User user = new User();
        // 判断数据类型
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LeYouException(ExceptionEnum.INVALID_USER_DATA_TYPE);
        }
        int count = this.userMapper.selectCount(user);
        return count == 0;
    }


    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendCode(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new LeYouException(ExceptionEnum.PHONE_IS_NULL);
        }
        // 生成验证码
        String code = RandomStringUtils.randomNumeric(6); //"234234"; // NumberUtils.generateCode(6);

        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);

        // 发送验证码
        amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", map);

        // 保存验证码
        // 生成key
        String key = KEY_PREFIX + phone;
        // 设置短信验证码 5 分钟有效
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

    }

    /***
     *
     *  用户注册功能
     *
     * @param user
     * @param code
     */
    public void reigsterUser(User user, String code) {

        // 从redis 中取出验证码
        String key = KEY_PREFIX + user.getPhone();
        String cacheCode = redisTemplate.opsForValue().get(key);
        // 校验验证码
        if (!org.apache.commons.lang3.StringUtils.equals(cacheCode, code)) {
            throw new LeYouException(ExceptionEnum.INVALID_VERIFY_CODE);
        }

        // 生成盐
        String salt = CodeUtils.generateSalt();
        user.setSalt(salt);
        // 对密码进行加密
        String password = CodeUtils.md5Hex(user.getPassword(), salt);
        user.setPassword(password);

        user.setCreated(new Date());
        // 写入数据库
        userMapper.insert(user);

    }

    /**
     * 根据用户名和密码查询用户
     *
     * @param username
     * @param password
     * @return
     */
    public User queryByUser(String username, String password) {
        // 查询用户
        User user = new User();

        user.setUsername(username);

        User record = this.userMapper.selectOne(user);

        // 校验
        if (record == null) {
            throw new LeYouException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        // 校验密码
        String passwd = CodeUtils.md5Hex(password, record.getSalt());
        if (!org.apache.commons.lang3.StringUtils.equals(passwd, record.getPassword())) {
            throw new LeYouException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        return record;
    }
}
